package MLDA_Process;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import Commons.IOUtil;

public class PAM4ST_V5 implements Runnable {

    public int K1 = 1000;
    public int K2 = 100;

    public int M;
    public int V;

    public double alpha1 = 0.1;
    public double alpha2 = 0.1;

    public double beta = 0.01;

    public int mp[];

    public int npk[][];
    public int npkSum[];

    public int nkw[][];
    public int nkwSum[];

    public int zAssigns_1[];
    public int zAssigns_2[];

    public int niters = 100;
    public int saveStep = 0;
    public String inputPath = "";
    public String outputPath = "";

    public int innerSteps = 1;

    public List<List<Integer>> docs = new ArrayList<List<Integer>>();
    public HashMap<String, Integer> w2i = new HashMap<String, Integer>();
    public HashMap<Integer, String> i2w = new HashMap<Integer, String>();

    public PAM4ST_V5() {
    }

    public PAM4ST_V5(int P, int K, int iter, int innerStep, int saveStep, double alpha1, double alpha2, double beta, String inputPath, String outputPath) {
        this.K1 = P;
        this.K2 = K;
        this.niters = iter;
        this.innerSteps = innerStep;
        this.saveStep = saveStep;
        this.alpha1 = alpha1;
        this.alpha2 = alpha2;
        this.beta = beta;
        this.inputPath = inputPath;
        this.outputPath = outputPath;
    }

    public void loadTxts(String txtPath) {
        BufferedReader reader = IOUtil.getReader(txtPath, "UTF-8");

        String line;
        try {
            line = reader.readLine();
            while (line != null) {
                List<Integer> doc = new ArrayList<Integer>();

                String[] tokens = line.trim().split("\\s+");
                for (String token : tokens) {
                    if (!w2i.containsKey(token)) {
                        w2i.put(token, w2i.size());
                        i2w.put(w2i.get(token), token);
                    }
                    doc.add(w2i.get(token));
                }
                docs.add(doc);
                line = reader.readLine();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        M = docs.size();
        V = w2i.size();

        return;
    }

    public void initSTPAM() {
        mp = new int[K1];

        npk = new int[K1][K2];
        npkSum = new int[K1];

        nkw = new int[K2][V];
        nkwSum = new int[K2];

        zAssigns_1 = new int[M];
        zAssigns_2 = new int[M];

        for (int m = 0; m != M; m++) {
            int z1 = (int) Math.floor(Math.random() * K1);
            zAssigns_1[m] = z1;
            mp[z1]++;

            int z2 = (int) Math.floor(Math.random() * K2);
            zAssigns_2[m] = z2;
            npk[z1][z2]++;
            npkSum[z1]++;

            for (int n = 0; n != docs.get(m).size(); n++) {
                int w = docs.get(m).get(n);

                nkw[z2][w]++;
                nkwSum[z2]++;
            }
        }
    }

    public void sampleZ1(int m) {
        int z1 = zAssigns_1[m];
        int z2 = zAssigns_2[m];
        mp[z1]--;
        npk[z1][z2]--;
        npkSum[z1]--;

        double[] pTable = new double[K1];

        for (int k = 0; k != K1; k++) {
            pTable[k] = (mp[k] + alpha1) / (M + K1 * alpha1)
                    * (npk[k][z2] + alpha2) / (npkSum[k] + K2 * alpha2);
        }

        for (int k = 1; k != K1; k++) {
            pTable[k] += pTable[k - 1];
        }

        double r = Math.random() * pTable[K1 - 1];

        for (int k = 0; k != K1; k++) {
            if (pTable[k] > r) {
                z1 = k;
                break;
            }
        }

        mp[z1]++;
        npk[z1][z2]++;
        npkSum[z1]++;

        zAssigns_1[m] = z1;
    }

    public void sampleZ2(int m) {
        HashMap<Integer, Integer> w2c = new HashMap<Integer, Integer>();
        int z1 = zAssigns_1[m];
        int z2 = zAssigns_2[m];
        int N = docs.get(m).size();
        for (int n = 0; n != N; n++) {
            int w = docs.get(m).get(n);
            if (!w2c.containsKey(w)) {
                w2c.put(w, 1);
            } else {
                w2c.put(w, w2c.get(w) + 1);
            }
            nkw[z2][w]--;
            nkwSum[z2]--;
        }
        npk[z1][z2]--;
        npkSum[z1]--;

        double VBeta = V * beta;
        double[] pTable = new double[K2];

        for (int k = 0; k != K2; k++) {
            List<Double> devidents = new ArrayList<Double>();

            for (int n = 0; n != N; n++) {
                devidents.add(VBeta + nkwSum[k] + n);
            }

            double expectTM = 1.0;
            int index = 0;
            for (int w : w2c.keySet()) {
                int c = w2c.get(w);
                for (int i = 0; i != c; i++) {
                    expectTM *= (nkw[k][w] + beta + i) / devidents.get(index++);
                }
            }

            pTable[k] = (npk[z1][k] + alpha2) / (npkSum[z1] + K2 * alpha2) * expectTM;
        }

        for (int k = 1; k != K2; k++) {
            pTable[k] += pTable[k - 1];
        }

        double r = Math.random() * pTable[K2 - 1];

        for (int k = 0; k != K2; k++) {
            if (pTable[k] > r) {
                z2 = k;
                break;
            }
        }

        for (int n = 0; n != N; n++) {
            int w = docs.get(m).get(n);
            nkw[z2][w]++;
            nkwSum[z2]++;
        }
        npk[z1][z2]++;
        npkSum[z1]++;

        zAssigns_2[m] = z2;
    }

    public void estimate() {
        long start = 0;
        for (int iter = 0; iter != niters; iter++) {
            start = System.currentTimeMillis();
            System.out.println("SPAM Iteration: " + iter + " ...");
            if (iter % this.saveStep == 0 && iter != 0 && iter != this.niters - 1) {
                this.storeResult(iter);
            }
            for (int i = 0; i != innerSteps; i++) {
                for (int m = 0; m != M; m++) {
                    this.sampleZ1(m);
                }
            }
            for (int i = 0; i != innerSteps; i++) {
                for (int m = 0; m != M; m++) {
                    this.sampleZ2(m);
                }
            }
            System.out.println("cost time:" + (System.currentTimeMillis() - start));
        }
        return;
    }

    public double[][] computePhi() {
        double[][] phi = new double[K2][V];
        for (int k = 0; k != K2; k++) {
            for (int v = 0; v != V; v++) {
                phi[k][v] = (nkw[k][v] + beta) / (nkwSum[k] + V * beta);
            }
        }
        return phi;
    }

    public ArrayList<List<Entry<String, Double>>> sortedTopicWords(
            double[][] phi, int T) {
        ArrayList<List<Entry<String, Double>>> res = new ArrayList<List<Entry<String, Double>>>();
        for (int k = 0; k != T; k++) {
            HashMap<String, Double> term2weight = new HashMap<String, Double>();
            for (String term : w2i.keySet())
                term2weight.put(term, phi[k][w2i.get(term)]);

            List<Entry<String, Double>> pairs = new ArrayList<Entry<String, Double>>(
                    term2weight.entrySet());
            Collections.sort(pairs, new Comparator<Entry<String, Double>>() {
                public int compare(Entry<String, Double> o1,
                                   Entry<String, Double> o2) {
                    return (o2.getValue().compareTo(o1.getValue()));
                }
            });
            res.add(pairs);
        }
        return res;
    }

    public void printTopics(int top_n) {
        double[][] phi = computePhi();
        ArrayList<List<Entry<String, Double>>> pairsList = this
                .sortedTopicWords(phi, K2);
        for (int k = 0; k != K2; k++) {
            System.out.println("Topic " + k + ":");
            for (int i = 0; i != top_n; i++) {
                System.out.println(pairsList.get(k).get(i).getKey() + " "
                        + pairsList.get(k).get(i).getValue());
            }
        }
    }

    public void printTopics(String path, int top_n) throws IOException {
        BufferedWriter writer = IOUtil.getWriter(path);
        double[][] phi = computePhi();
        ArrayList<List<Entry<String, Double>>> pairsList = this
                .sortedTopicWords(phi, K2);
        for (int k = 0; k != K2; k++) {
            writer.write("Topic " + k + ":\n");
            for (int i = 0; i != top_n; i++) {
                writer.write(pairsList.get(k).get(i).getKey() + " "
                        + pairsList.get(k).get(i).getValue() + "\n");
            }
        }
        writer.close();
    }

    public void savePhi(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");

        double[][] phi = computePhi();
        int K = phi.length;
        assert K > 0;
        int V = phi[0].length;

        try {
            for (int k = 0; k != K; k++) {
                for (int v = 0; v != V; v++)
                    writer.append(phi[k][v] + " ");
                writer.append("\n");
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public void saveWordmap(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");

        try {
            for (String word : w2i.keySet())
                writer.append(word + "\t" + w2i.get(word) + "\n");

            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    public void saveAssign(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");
        try {
            for (int i = 0; i < zAssigns_2.length; i++) {
                writer.write(zAssigns_1[i] + ":" + zAssigns_2[i] + "\n");
            }

            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return;
    }

    public void saveTheta(String path) {
        BufferedWriter writer = IOUtil.getWriter(path, "utf-8");
        double[][] theta = new double[M][K2];
        try {
            for (int m = 0; m != M; m++) {
                for (int k = 0; k != K2; k++) {
                    if (zAssigns_2[m] == k) {
                        theta[m][k] = (docs.get(m).size() + alpha2) / (docs.get(m).size() + K2 * alpha2);
                    } else {
                        theta[m][k] = (0.0 + alpha2) / (0.0 + K2 * alpha2);
                    }
                    writer.append(theta[m][k] + " ");
                }
                writer.newLine();
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void printModel() {
        System.out.println("\tK1 :" + this.K1 +
                "\tK2 :" + this.K2 +
                "\tniters :" + this.niters +
                "\tinnerSteps :" + this.innerSteps +
                "\tsaveStep :" + this.saveStep +
                "\talpha1 :" + this.alpha1 +
                "\talpha2 :" + this.alpha2 +
                "\tbeta :" + this.beta +
                "\tinputPath :" + this.inputPath +
                "\toutputPath :" + this.outputPath);
    }

    public void storeResult(int times) {
        String appendString = "final";
        if (times != 0) {
            appendString = times + "";
        }
        try {
            this.printTopics(outputPath + "/model-" + appendString + ".twords", 20);
            this.saveWordmap(outputPath + "/wordmap.txt");
            this.savePhi(outputPath + "/model-" + appendString + ".phi");
            this.saveAssign(outputPath + "/model-" + appendString + ".tassign");
            this.saveTheta(outputPath + "/model-" + appendString + ".theta");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void run() {
        printModel();
        this.loadTxts(inputPath);//
        this.initSTPAM();
        this.estimate();
        this.storeResult(0);

    }

    public static void PAMForShortText_V5(int P, int K, int iter, int innerStep, int saveStep, double alpha1, double alpha2, double beta, int threadNum, String path) {
        ExecutorService service = Executors.newCachedThreadPool();
        File trainFile = new File(path);
        String parent_path = trainFile.getParentFile().getAbsolutePath() + "/PAM4ST_V5_" + P + "_" + K + "_" + alpha1 + "_" + alpha2 + "_" + beta + "/";
        for (int i = 0; i < threadNum; i++) {
            (new File(parent_path + i)).mkdirs();
            service.submit(new PAM4ST_V5(P, K, iter, innerStep, saveStep, alpha1, alpha2, beta, path, parent_path + i));

        }
        service.shutdown();
    }
}
